//1.引入express
const express = require('express');

//2.创建应用对象
const app = express();

//3.创建路由规划
//request是对请求报文的封装
//response是对响应报文的封装
app.get('/server',(request,response)=>{
    //设置响应头 设置允许跨域
    response.setHeader('Access-Control-Allow-Origin','*');
     //设置响应
     response.send('HELLO AJAX');
});
app.post('/server',(request,response)=>{
    //设置响应头 设置允许跨域
    response.setHeader('Access-Control-Allow-Origin','*');
     //设置响应
     response.send('HELLO AJAX POST');
});
app.all('/json-server',(request,response)=>{
    //设置响应头 设置允许跨域
    response.setHeader('Access-Control-Allow-Origin','*');
     //设置响应
    response.setHeader('Access-Control-Allow-Headers','*')
     const data = {
         name : 'migu'
     };
     let str = JSON.stringify(data);
     response.send(str);
});
//ie缓存问题
app.get('/ie',(request,response)=>{
    //设置响应头 设置允许跨域
    response.setHeader('Access-Control-Allow-Origin','*');
     //设置响应
     response.send('HELLO AJAX-1');
});
//超时和网络异常
app.get('/delay',(request,response)=>{
    //设置响应头 设置允许跨域
    response.setHeader('Access-Control-Allow-Origin','*');
     //设置响应
     setTimeout(() =>{
         response.send('延时响应');
     },3000)
});
//jQuery发送请求
app.all('/jQuery-server',(request,response)=>{
    //设置响应头 设置允许跨域
    response.setHeader('Access-Control-Allow-Origin','*');
     //设置响应
     const data = {name : 'littlebr'}
     response.send(JSON.stringify(data));
});
app.all('/axios-server',(request,response)=>{
    //设置响应头 设置允许跨域
    response.setHeader('Access-Control-Allow-Origin','*');
     //设置响应
     response.setHeader('Access-Control-Allow-Headers','*');
     response.send('hello axios');
});

app.all('/fetch-server',(request,response)=>{
    //设置响应头 设置允许跨域
    response.setHeader('Access-Control-Allow-Origin','*');
     //设置响应
     response.setHeader('Access-Control-Allow-Headers','*');
     const data = {name : 'littlebr'}
     response.send(JSON.stringify(data));
});

app.all('/check-username',(request,response)=>{
    const data = {
        exist:1,
        msg:'用户名已存在'
    };
    let str =  JSON.stringift(data);
    response.send(`handle(${str})`);
});

app.all('/jquery-jsonp-server',(request,response)=>{
    const data = {
        name:'little',
        city:['北京','上海']
    };
    let str =  JSON.stringift(data);
    let cb = request.query.callback;
    response.end(`handle(${cb}${str})`);
});
//4.监听端口启动服务
app.listen(8000,()=>{
    console.log("服务已经启动，8000端口监听中...");
})